"use client";

import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Form,
  Input,
  Button,
  DatePicker,
  Space,
  Modal,
  message,
} from "antd";
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import MainLayout from "@/components/layouts/MainLayout";
import {
  getSubsidyList,
  createSubsidy,
  updateSubsidy,
  deleteSubsidy,
} from "@/services/subsidy";

const { RangePicker } = DatePicker;

// 首先定义接口类型
interface SubsidyRecord {
  id: string;
  status: string;
  createTime: string;
  updateTime: string;
  applyTotalNum: number;
  applyOilNum: number;
  applyEleNum: number;
  applyTotalApprovedNum: number;
  applyOilApprovedNum: number;
  applyEleApprovedNum: number;
  year: string;
  month: string;
}

export default function Subsidy() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<SubsidyRecord[]>([]);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<SubsidyRecord | null>(
    null
  );

  const columns = [
    {
      title: "年份",
      dataIndex: "year",
      key: "year",
      align: "center" as const,
    },
    {
      title: "月份",
      dataIndex: "month",
      key: "month",
      align: "center" as const,
    },
    {
      title: "国补申请量",
      children: [
        {
          title: "燃油车",
          dataIndex: "applyOilNum",
          key: "applyOilNum",
          align: "center" as const,
        },
        {
          title: "新能源汽车",
          dataIndex: "applyEleNum",
          key: "applyEleNum",
          align: "center" as const,
        },
        {
          title: "合计",
          dataIndex: "applyTotalNum",
          key: "applyTotalNum",
          align: "center" as const,
        },
      ],
    },
    {
      title: "初审通过量",
      children: [
        {
          title: "燃油车",
          dataIndex: "applyOilApprovedNum",
          key: "applyOilApprovedNum",
          align: "center" as const,
        },
        {
          title: "新能源汽车",
          dataIndex: "applyEleApprovedNum",
          key: "applyEleApprovedNum",
          align: "center" as const,
        },
        {
          title: "合计",
          dataIndex: "applyTotalApprovedNum",
          key: "applyTotalApprovedNum",
          align: "center" as const,
        },
      ],
    },
    {
      title: "操作",
      key: "action",
      align: "center" as const,
      render: (_: unknown, record: SubsidyRecord) => (
        <Space>
          <Button
            type="primary"
            onClick={() => handleEdit(record)}
            icon={<EditOutlined />}
          >
            编辑
          </Button>
          <Button
            onClick={() => handleDelete(record)}
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const fetchData = async () => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const res = await getSubsidyList(values);
      setData(res.data);
    } catch (error) {
      message.error("获取数据失败");
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingRecord(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record: SubsidyRecord) => {
    setEditingRecord(record);
    form.setFieldsValue({
      year: record.year,
      month: record.month,
      gasApplication: record.applyOilNum,
      newEnergyApplication: record.applyEleNum,
      gasApproved: record.applyOilApprovedNum,
      newEnergyApproved: record.applyEleApprovedNum,
    });
    setIsModalVisible(true);
  };

  const handleDelete = async (record: SubsidyRecord) => {
    try {
      await deleteSubsidy(record.id);
      message.success("删除成功");
      fetchData();
    } catch (error) {
      message.error("删除失败");
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingRecord) {
        await updateSubsidy(editingRecord.id, values);
        message.success("更新成功");
      } else {
        await createSubsidy(values);
        message.success("创建成功");
      }
      setIsModalVisible(false);
      fetchData();
    } catch (error) {
      message.error("操作失败");
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <MainLayout>
      <Card>
        <Space direction="vertical" style={{ width: "100%", marginBottom: 12 }}>
          <Form form={searchForm} layout="inline">
            <Form.Item name="dateRange" label="日期范围">
              <RangePicker picker="month" />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  onClick={fetchData}
                  icon={<SearchOutlined />}
                >
                  查询
                </Button>
                <Button
                  onClick={() => searchForm.resetFields()}
                  icon={<ReloadOutlined />}
                >
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>

          <Button
            type="primary"
            onClick={handleAdd}
            style={{ marginTop: 6 }}
            icon={<PlusOutlined />}
          >
            新增
          </Button>
        </Space>

        <Table
          loading={loading}
          columns={columns}
          dataSource={data}
          rowKey="id"
          bordered
        />

        <Modal
          title={editingRecord ? "编辑补贴" : "新增补贴"}
          open={isModalVisible}
          onOk={handleModalOk}
          onCancel={() => setIsModalVisible(false)}
        >
          <Form form={form} layout="vertical">
            <Form.Item name="month" label="月份" rules={[{ required: true }]}>
              <Input type="number" />
            </Form.Item>
            <Form.Item name="year" label="年份" rules={[{ required: true }]}>
              <Input type="number" />
            </Form.Item>
            <Form.Item
              name="gasApplication"
              label="燃油车申请量"
              rules={[{ required: true }]}
            >
              <Input type="number" />
            </Form.Item>
            <Form.Item
              name="newEnergyApplication"
              label="新能源汽车申请量"
              rules={[{ required: true }]}
            >
              <Input type="number" />
            </Form.Item>
            <Form.Item
              name="gasApproved"
              label="燃油车通过量"
              rules={[{ required: true }]}
            >
              <Input type="number" />
            </Form.Item>
            <Form.Item
              name="newEnergyApproved"
              label="新能源汽车通过量"
              rules={[{ required: true }]}
            >
              <Input type="number" />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </MainLayout>
  );
}
